#include "server.h"
//#include <QJsonArray>
//#include <QJsonDocument>
//#include <QJsonObject>
//#include <QJsonParseError>
#include <QThread>
#include "hereyou/IReceiveWebServiceSOAP11Binding.nsmap"
#define API_GOODS_FETCH "/uapws/service/receiveservice?wsdl"

server::server(QObject *parent) : QObject(parent)
{
    manager = new QNetworkAccessManager(this);
    config = CabinetConfig::config();
    reply_goods_fetch = NULL;
    info = NULL;
}

void server::setServerAddress(QString address)
{
    serverAddress = address.toLocal8Bit();
}

#include <QDateTime>
void server::test()
{
    if(info != NULL)
        delete info;

    info = new ctrlInfo();
    info->caseNbr = "E" + QTime::currentTime().toString("hhmmss").right(4);

    QByteArray qba = QByteArray("{\"type\":\"0\",\"msg\":\"成功\",\"goods_opcode\":\"T0001\",\"goods_name\":\"测试物品\",\"goods_desc\":\"盒\",\"product_location\":\"测试厂家\",\"num\":\"1\",\"goods_registration\":\"TR123456\",\"retail_money\":\"25\",\"retail_price\":\"1.0000000000\"}");
//    QString cTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    recv_goods_fetch(qba, QDateTime::currentDateTime());
}

QByteArray server::xml_fetch_goods(QString departId, QString userId, QString goodsId)
{
    QByteArray ret = QString("<?xml version=\"1.0\" encoding=\"UTF-8\"?><env:Envelop xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:sn=\"http://webservice.pub.itf.com/IReceiveWebService\"><env:Header/><env:Body><sn:doDepotCaseConsume><string>[{\"COM_DEPOT_CODE\":\"%1\",\"USER_CODE\":\"%2\",\"CASE_NBR\":\"%3\"}]</string></sn:doDepotCaseConsume></env:Body></env:Envelop>").arg(departId).arg(userId).arg(goodsId).toLocal8Bit();
    return ret;
}

QByteArray server::readXmlRst(QByteArray rst)
{
    QXmlStreamReader reader(rst);
    QByteArray ret = "-1";
//    QString msg = QString();

    while(!reader.atEnd())
    {
        if(reader.isStartElement())
        {
            if(reader.name() == QString("return"))
            {
                reader.readNext();
                ret = reader.text().toUtf8();
                ret.remove(0, 1);
                ret.remove(ret.size()-1, 1);
                qDebug()<<"[ret]:"<<ret;
                return ret;
            }
//            else if(reader.name() == QString("define"))
//            {
//                reader.readNext();
//                qDebug()<<"[define]"<<reader.text();
//            }
        }
        reader.readNext();
    }
    return ret;
}

void server::fetchGoods(QString departId, QString userId, QString goodsId)
{
//    soap hSoap;
//    soap_init(&hSoap);
//    soap_set_mode(&hSoap, SOAP_C_UTFSTRING);

//    _ns1__doDepotCaseConsume request;
//    _ns1__doDepotCaseConsumeResponse response;

//    QByteArray qba = QString("[{\"COM_DEPOT_CODE\":\"%1\",\"USER_CODE\":\"%2\",\"CASE_NBR\":\"%3\"}]").arg(departId).arg(userId).arg(goodsId).toLocal8Bit();
//    request.string = qba.data();
//    qDebug()<<"[soap]"<<serverAddress<<qba;
//    soap_call___ns1__doDepotCaseConsume(serverAddress.data() ,&hSoap, NULL, NULL, &request, response);

//    if(hSoap.error)
//    {
//        soap_end(&hSoap);
//        qDebug()<<"[fetchGoods]"<<"soap error";
//        emit fetch_goods_rst("服务器通信失败");
//        return;
//    }

//    soap_end(&hSoap);
//    qDebug()<<response.return_;
//    recv_goods_fetch(QByteArray(response.return_));

    QString nUrl = QString(serverAddress);//"http://hereyou.imwork.net:9091/uapws/service/receiveservice";
    QByteArray qba = xml_fetch_goods(departId, userId, goodsId);
    if(info != NULL)
        delete info;

    info = new ctrlInfo();
    info->caseNbr = goodsId;
    qDebug()<<"[fetchGoods]"<<nUrl;
    qDebug()<<qba;
    QNetworkRequest request;
    request.setRawHeader("Content-Type", "application/x-www-form-urlencoded");//"application/soap+xml;charset=utf-8");//"application/x-www-form-urlencoded"
    request.setRawHeader("X-Requested-With","XMLHttpRequest");
    request.setUrl(nUrl);
    if(reply_goods_fetch != NULL)
    {
        reply_goods_fetch->deleteLater();
    }
    reply_goods_fetch = manager->post(request, qba);
    connect(reply_goods_fetch, SIGNAL(readyRead()), this, SLOT(recv_goods_fetch()));
}


void server::recv_goods_fetch(QByteArray qba, QDateTime curT)
{
//    QString msg = QString(qba);
//    int idx[3];
//    idx[0] = msg.indexOf("msg",3);
//    qDebug()<<msg<<idx[0];
//    if(idx[0] == -1)
//    {
//        qDebug()<<"msg 定位失败"<<idx[0];
//        emit fetch_goods_rst("失败");
//        return;
//    }
//    idx[1] = msg.indexOf('"', idx[0]+4);
//    idx[2] = msg.indexOf('"', idx[1]+1);
//    emit fetch_goods_rst(msg.mid(idx[1]+1, idx[2]-idx[1]-2));
    QByteArray qbaRet = readXmlRst(qba);
    if(qbaRet.size() < 3)
        return;
//        qbaRet = qba;

    cJSON* json = cJSON_Parse(qbaRet.data());
    if(json != NULL)
    {
        QString jType = QString::fromUtf8(cJSON_GetObjectItem(json, "type")->valuestring);
        QString jMsg = QString::fromUtf8(cJSON_GetObjectItem(json, "msg")->valuestring);
        qDebug()<<"[msg]"<<jMsg;
        emit fetch_goods_rst(jMsg);
        if(jType == "0")
        {
            info->goodsOpcode = QString::fromUtf8(cJSON_GetObjectItem(json, "goods_opcode")->valuestring);
            info->goodsName = QString::fromUtf8(cJSON_GetObjectItem(json, "goods_name")->valuestring);
            info->goodsDesc = QString::fromUtf8(cJSON_GetObjectItem(json, "goods_desc")->valuestring);
            info->productLocation = QString::fromUtf8(cJSON_GetObjectItem(json, "product_location")->valuestring);
            info->num = QString::fromUtf8(cJSON_GetObjectItem(json, "num")->valuestring);
            info->goodsRegistration = QString::fromUtf8(cJSON_GetObjectItem(json, "goods_registration")->valuestring);
            info->goodsUnitPrice = QString::fromUtf8(cJSON_GetObjectItem(json, "retail_price")->valuestring);
            info->goodsSumMoney = QString::fromUtf8(cJSON_GetObjectItem(json, "retail_money")->valuestring);

            UserInfo* uInfo = config->getCurUser();
            if(uInfo == NULL)
            {
                info->userCode = QString();
                info->userName = QString();
                info->timeConsuming = curT;
            }
            else
            {
                info->userCode = config->getCurUser()->id;
                info->userName = config->getCurUser()->name;
                info->timeConsuming = curT;
            }
            emit new_report(info);
        }
    }


//    QJsonParseError jsonError;
//    QJsonDocument document = QJsonDocument::fromJson(qbaRet, &jsonError);
//    if(!document.isNull() && jsonError.error == QJsonParseError::NoError)
//    {
//        if(document.isObject())
//        {
//            QJsonObject object = document.object();
//            QJsonValue value = getJsonValue(object, "type");
//            QJsonValue jMsg = getJsonValue(object, "msg");
//            QString msg = jMsg.toString();
//            qDebug()<<"[msg]"<<msg;
//            emit fetch_goods_rst(msg);
//            if(value.toString() == "0")
//            {
//                info->goodsOpcode = getJsonValue(object, "goods_opcode").toString();
//                info->goodsName = getJsonValue(object, "goods_name").toString();
//                info->goodsDesc = getJsonValue(object, "goods_desc").toString();
//                info->productLocation = getJsonValue(object, "product_location").toString();
//                info->num = getJsonValue(object, "num").toString();
//                info->goodsRegistration = getJsonValue(object, "goods_registration").toString();
//                info->goodsUnitPrice = getJsonValue(object, "retail_price").toString();
//                info->goodsSumMoney = getJsonValue(object, "retail_money").toString();

//                UserInfo* uInfo = config->getCurUser();
//                if(uInfo == NULL)
//                {
//                    info->userCode = QString();
//                    info->userName = QString();
//                    info->timeConsuming = curT;
//                }
//                else
//                {
//                    info->userCode = config->getCurUser()->id;
//                    info->userName = config->getCurUser()->name;
//                    info->timeConsuming = curT;
//                }
//                emit new_report(info);
//            }
//            else
//            {

//            }
//        }
//    }
}

//QJsonValue server::getJsonValue(QJsonObject object, QString key)
//{
//    if(!object.contains(key))
//        return QJsonValue();

//    return object.value(key);
//}

QDateTime server::getServerTime(QString sTime)
{
    QDateTime serverTime = QDateTime::fromString(sTime ,"ddd, dd MMM yyyy hh:mm:ss");
    serverTime.setTimeSpec(Qt::UTC);
    qDebug()<<"curTime:"<<curTime;
    qDebug()<<serverTime.toLocalTime().toString();
    return serverTime.toLocalTime();
}

void server::recv_goods_fetch()
{
    QByteArray qba = reply_goods_fetch->readAll();
    qDebug()<<"recv_goods_fetch"<<qba;
//    curTime = getServerTime(QString(reply_goods_fetch->rawHeader("Date")));
    curTime = QDateTime::currentDateTime();
    recv_goods_fetch(qba, curTime);
    reply_goods_fetch->deleteLater();
    reply_goods_fetch = NULL;
}

